import pymysql
from flask import Flask, request, render_template
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import requests

host = '43.142.44.130'
user = 'xiaoxueqi'
db = 'xiaoxueqi'
password = '123456'
port = 3306


def conectsql():
    conn = pymysql.connect(
        host=host,
        user=user,
        db=db,
        charset='utf8',
        password=password,
        port=port
    )
    cursor = conn.cursor()
    return conn, cursor


def ReadMedical(province, city):
    conn, cls = conectsql()
    # 3.创建sql语句
    a = ['name', 'phone', 'pos']
    sql = "select name,phone,pos from medical where province like '%{}%' and city like '%{}%'".format(province, city)
    print(sql)
    cls.execute(sql)
    result = cls.fetchall()
    resultdata = []
    for i in result:
        resultdata.append(dict(zip(a, i)))
    print(result)
    for i in resultdata:
        print(i)
    conn.close()
    return resultdata


def get_policies(from_city: str, to_city: str) -> str:
    """
    双向出行政策
    :param from_city: 出发城市
    :param to_city: 抵达城市
    :return:
    """
    url_city_list = 'https://r.inews.qq.com/api/trackmap/citylist?'
    city_list_raw = requests.get(url_city_list)
    city_list = city_list_raw.json()
    msg = ""
    from_id = ''
    to_id = ''
    from_city = from_city.split()[0]
    to_city = to_city.split()[0]
    if city_list['status'] == 0 and city_list['message'] == "success":
        for province in city_list['result']:
            for city in province['list']:
                if from_city == city['name']:
                    from_id = city['id']
                if to_city == city['name']:
                    to_id = city['id']
    else:
        msg += "城市列表请求错误"
        return msg

    try:
        url_get_policy = f"https://r.inews.qq.com/api/trackmap/citypolicy?&city_id={from_id},{to_id}"
    except UnboundLocalError:
        msg += "城市名错误"
        return msg

    policy_raw = requests.get(url_get_policy)
    policy = policy_raw.json()
    if policy['status'] == 0 and policy['message'] == "success":
        try:
            data_leave = policy['result']['data'][0]
            data_to = policy['result']['data'][1]
            if from_city == to_city and data_leave['leave_policy'].strip() == data_to['back_policy'].strip():
                msg += f"{from_city}出入政策：\n"
                msg += f"{data_to['back_policy'].strip()}\n于{data_to['back_policy_date']}更新\n\n"
                msg += "\n"
            else:
                msg += f"{from_city}离开政策：\n{data_leave['leave_policy'].strip()}\n于{data_leave['leave_policy_date']}更新\n\n"
                msg += f"{to_city}进入政策：\n{data_to['back_policy'].strip()}\n于{data_to['back_policy_date']}更新\n\n"
            msg += f"{to_city}酒店政策：{data_to['stay_info'].strip()}\n\n"
            msg += "免责声明：以上所有数据来源于腾讯新闻出行防疫政策查询"
        except IndexError:
            msg = ''
    else:
        msg += "政策请求错误"
    return msg


def get_result(identify_code: str):
    chrome_options = Options()
    # 设置chrome浏览器无界面模式
    chrome_options.add_argument('--headless')
    browser = webdriver.Chrome(options=chrome_options)

    browser.get(
        'https://broccoli.uc.cn/apps/feiyansearch/routes/d_beY5eo?uc_param_str=dsdnfrpfbivesscpgimibtbmnijblauputogpintnwktprchmt&fromsource=feiyan')
    # 设置超时，过1秒钟还未获取结果要么无数据，要么车次信息有误
    browser.implicitly_wait(1)
    # 模拟查询
    browser.find_element(By.ID, 'fy-search-ipt2').send_keys(identify_code)
    browser.find_element(By.CLASS_NAME, 'search_btn').click()
    # 等待页面加载
    time.sleep(0.1)
    # 处理数据
    data = browser.find_elements(By.CLASS_NAME, 'search_item')
    list_total = []
    # 判断是否有数据
    if len(data) > 0:
        for i in data:
            list_temp = []  # 分别为出行方式，车次，发生时间，出发站，到达站，描述（可能有），消息来源
            # 获取发生时间,出行方式
            first_line = i.find_element(By.CLASS_NAME, 'item_line1')
            div1 = first_line.find_elements(By.TAG_NAME, 'div')
            # 出行方式
            out_type = div1[0].text[0:2]
            list_temp.append(out_type)
            list_temp.append(identify_code)
            # 发生时间
            occur_time = div1[1].text
            list_temp.append(occur_time)
            # print(out_type)

            # 获取出发地点，到达地点和数据来源
            second_line = i.find_element(By.CLASS_NAME, 'item_left')
            div2 = second_line.find_elements(By.TAG_NAME, 'div')
            # 出发地点和到达地点
            fonts = div2[0].find_elements(By.TAG_NAME, 'font')
            try:
                from_place = fonts[0].text[3:]
                to_place = fonts[1].text[3:]
                list_temp.append(from_place)
                list_temp.append(to_place)
            except IndexError:
                error_msg = "该记录出现疫情，但没有记录出发站或到达站"
                return error_msg
            # print(from_place, to_place)
            # 获取来源
            if len(div2) < 3:
                source = div2[1].text[3:]
                list_temp.append(source)
            else:
                describe = div2[1].text[3:]
                source = div2[2].text[3:]
                list_temp.append(describe)
                list_temp.append(source)
            # print(list_temp)
            list_total.append(list_temp)
        return list_total
    else:
        # print('若您输入的航班号或车次无误，则没有疫情发生')
        msg = '若您输入的航班号或车次无误，则没有疫情发生'
        return msg


grade_url = "https://wechat.wecity.qq.com/api/PneumoniaTravelNoAuth/queryAllRiskLevel"


def get_risk(area):
    type_ = ''

    area = area.split()[0]
    if "省" in area:
        area = area.split("省")[0]
        type_ = "(省)"
    if "市" in area:
        area = area.split("市")[0]
        type_ = "(市)"
    if area in ["北京", "天津", "重庆", "上海"]:
        type_ = "(直辖市)"
    if area in ["香港", "澳门"]:
        type_ = "(特别行政区)"
    if area == "内蒙古自治区":
        area = "内蒙古"
    elif area == "宁夏回族自治区":
        area = "宁夏"
    elif area == "新疆维吾尔自治区":
        area = "新疆"
    elif area == "西藏自治区":
        area = "西藏"
    elif area == "广西壮族自治区":
        area = "广西"
    payload_json = {
        "args": {"req": {}},
        "service": "PneumoniaTravelNoAuth",
        "func": "queryAllRiskLevel",
        "context": {"userId": "a"},
    }
    risk_area_data = requests.post(url=grade_url, json=payload_json)
    risk_area_data = risk_area_data.json()
    risk_area_data = risk_area_data["args"]["rsp"]

    mediumRiskAreaList = risk_area_data["mediumRiskAreaList"]
    highRiskAreaList = risk_area_data["highRiskAreaList"]
    # print(mediumRiskAreaList)
    if area != 'None':
        msg = "—{}{}新冠肺炎疫情最新动态—\n\n🔰 中风险地区：".format(area, type_)
        mid_risk_msg = ""
        for i in mediumRiskAreaList:
            for j in i["list"]:
                if j["cityName"] in [area, area + "市"] or j["provinceName"] in [area, area + "省"]:
                    mid_risk_msg += f"\n🪐 {j['cityName'] + j['areaName']} \n🏠 {j['communityName']}\n"
        if len(mid_risk_msg) > 0:
            mid_risk_msg = mid_risk_msg.replace("、", "\n🏠 ")
            msg += "\n" + mid_risk_msg + "\n"
        else:
            msg += "暂无风险地区\n——————————————————\n\n"

        msg += "🔰 高风险地区："
        high_risk_msg = ""
        for i in highRiskAreaList:
            for j in i["list"]:
                if j["cityName"] in [area, area + "市"] or j["provinceName"] in [area, area + "省"]:
                    high_risk_msg += f"\n🪐 {j['cityName'] + j['areaName']} \n🏠 {j['communityName']}\n"
        if len(high_risk_msg) > 0:
            high_risk_msg = high_risk_msg.replace("、", "\n🏠 ")
            msg += "\n" + high_risk_msg + "\n"
        else:
            msg += "暂无风险地区"
        return msg
    else:
        msg = "—全国新冠肺炎疫情最新动态—\n\n🔰 中风险地区："
        mid_risk_msg = ""
        print('1111111111111111')
        for i in mediumRiskAreaList:
            for j in i["list"]:
                mid_risk_msg += f"\n🪐 {j['provinceName']}\n{j['cityName'] + j['areaName']} \n🏠 {j['communityName']}\n"
        if len(mid_risk_msg) > 0:
            mid_risk_msg = mid_risk_msg.replace("、", "\n🏠 ")
            msg += "\n" + mid_risk_msg + "\n"
        else:
            msg += "暂无风险地区\n——————————————————\n\n"

        msg += "🔰 高风险地区："
        high_risk_msg = ""
        for i in highRiskAreaList:
            for j in i["list"]:
                high_risk_msg += f"\n🪐 {j['provinceName']}\n{j['cityName'] + j['areaName']} \n🏠 {j['communityName']}\n"
        if len(high_risk_msg) > 0:
            high_risk_msg = high_risk_msg.replace("、", "\n🏠 ")
            msg += "\n" + high_risk_msg + "\n"
        else:
            msg += "暂无风险地区"
        return msg


app = Flask(__name__)


@app.route("/First")
def register():
    return render_template("First.html")


@app.route("/Second")
def register2():
    return render_template("Second.html")


@app.route("/中国")
def register6():
    return render_template("中国.html")


@app.route("/河南省")
def register7():
    return render_template("河南省.html")


@app.route("/郑州市")
def register8():
    return render_template("郑州市.html")


@app.route("/Forth")
def Forth():
    # 获取前端的数据
    # 获取用户名
    name = request.args.get("uname")
    # pwd = request.args.get("upwd")
    print("搜索内容：", name)  # ,"密码:",pwd)
    # 到数据库中添加数据
    conn = pymysql.connect(
        host="43.142.44.130",
        port=3306,
        db="xiaoxueqi",
        user="xiaoxueqi",
        password="123456",
        charset="utf8"
    )
    cls = conn.cursor()
    # sql="insert into myuser values(null,%s,%s)"
    # rows = cls.execute(sql,[name,pwd])
    # conn.commit()
    # if rows>=1:  #添加成功
    # 从数据库中查询用户信息，显示到前端
    sql2 = "select * from kepu order by count desc limit 5"
    cls.execute(sql2)
    result2 = cls.fetchall()

    if name is not None:
        sql = "select * from kepu where biaoti like '%" + name + "%'"
        cls.execute(sql)
        result = cls.fetchall()  # 元组类型
        conn.close()
        return render_template("Forth.html", res=result, res2=result2)
    else:
        sql = "select * from kepu"
        cls.execute(sql)
        result = cls.fetchall()  # 元组类型
        conn.close()
        return render_template("Forth.html", res=result, res2=result2)


@app.route("/Fifth")
def Fifth():
    # 获取前端的数据
    # 获取用户名
    name = request.args.get("uname")
    print("搜索内容：", name)  # ,"密码:",pwd)
    # 到数据库中添加数据
    conn = pymysql.connect(
        host="43.142.44.130",
        port=3306,
        db="xiaoxueqi",
        user="xiaoxueqi",
        password="123456",
        charset="utf8"
    )
    cls = conn.cursor()
    # sql="insert into myuser values(null,%s,%s)"
    # rows = cls.execute(sql,[name,pwd])
    # conn.commit()
    # if rows>=1:  #添加成功
    # 从数据库中查询用户信息，显示到前端
    # sql2="select * from yaoyan order by count desc limit 5"
    # cls.execute(sql2)
    # result2=cls.fetchall()

    if name is not None:
        sql = "select * from yaoyan where biaoti like '%" + name + "%'"
        cls.execute(sql)
        result = cls.fetchall()  # 元组类型
        conn.close()
        return render_template("Fifth.html", res=result)  # , res2=result2)
    else:
        sql = "select * from yaoyan"
        cls.execute(sql)
        result = cls.fetchall()  # 元组类型
        conn.close()
        return render_template("Fifth.html", res=result)  # , res2=result2)


@app.route('/Seven')
def seven():
    return render_template('Seven.html')


@app.route('/Eight', methods=['post', 'get'])
def Eight():
    if request.method == 'GET':
        return render_template('Eight.html')
    if request.method == 'POST':
        province = request.form.get('province')
        city = request.form.get('city')
        print(province)
        print(city)
        resultdata = ReadMedical(province, city)
        print(resultdata)
        return render_template('Eight.html', resultdata=resultdata)  # 将查询结果返回到前端


@app.route('/Nine')
def Nine():
    chrome_options = Options()
    # 设置chrome浏览器无界面模式
    chrome_options.add_argument('--headless')
    browser = webdriver.Chrome(options=chrome_options)
    browser.get('https://top.baidu.com/board?tab=realtime')
    # 前10条热搜
    data = browser.find_elements(By.CLASS_NAME, 'title_dIF3B')[1:11]
    list_total = []
    # 获取当前标签的href属性
    for p in data:
        key_value = [0, 0]
        key_value[1] = p.get_attribute('href')
        key_value[0] = p.find_element(By.TAG_NAME, 'div').text
        print(key_value)
        list_total.append(key_value)

    return render_template('Nine.html', res=list_total)


def Report(name, phone, content):
    conn, cls = conectsql()
    sql = 'insert into report values(%s,%s,%s)'
    cls.execute(sql, [name, phone, content])
    conn.commit()
    conn.close()


@app.route("/Tenth")
def Tenth():
    # 获取前端的数据
    # 获取用户名
    name = request.args.get("uname")
    print("搜索内容：", name)  # ,"密码:",pwd)

    risk = get_risk(str(name))
    return render_template("Tenth.html", res=risk)


@app.route('/Twelve', methods=['GET', 'POST'])
def Twelve():
    if request.method == 'GET':
        return render_template('Twelve.html')
    if request.method == 'POST':
        name = request.form.get('name')
        phone = request.form.get('phone')
        content = request.form.get('content')
        Report(name, phone, content)
        return render_template('Twelve.html')


def GetReport(phone):
    conn, cls = conectsql()
    a = ['content']
    sql = 'select content from report where phone=%s'
    cls.execute(sql, [phone])
    result = cls.fetchall()
    resultdata = []
    for i in result:
        resultdata.append(dict(zip(a, i)))
    for i in resultdata:
        print(i)
    conn.close()
    return resultdata


@app.route('/myreport', methods=['GET', 'POST'])
def myreport():
    if request.method == 'GET':
        return render_template('myreport.html')
    if request.method == 'POST':
        phone = request.form.get('phone')
        data = GetReport(phone)
        return render_template('myreport.html', data=data)


@app.route('/Thirteen')
def Thirteen():
    return render_template('Thirteen.html')


# 只有2020初-2021末车次航班数据
# 例子演示：G856  CZ6643 CZ2628 K287
@app.route('/Fifteen', methods=['GET', 'POST'])
def Fifteen():
    if request.method == 'GET':
        return render_template('Fifteen.html')
    if request.method == 'POST':
        search1 = request.form.get('uname')
        msg = get_result(search1)
        return render_template('Fifteen.html', msg=msg)


@app.route('/Forteen', methods=['GET', 'POST'])
def Forteen():
    if request.method == 'GET':
        return render_template('Forteen.html')
    if request.method == 'POST':
        search1 = request.form.get('uname1')
        search2 = request.form.get('uname2')
        print(search1, search2)
        msg = get_policies(search1, search2)
        return render_template('Forteen.html', msg=msg)


if __name__ == '__main__':
    app.run(debug=True)
